from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
import json
import hashlib
from user.models import UserProfile
from user.views import make_token
# Create your views here.

class TokenView(View):
    def post(self,request):
        json_str = request.body
        py_obj = json.loads(json_str)
        username = py_obj['username']
        password = py_obj['password']
        print(username,password)
        try:
            user = UserProfile.objects.get(username=username)
        except Exception as e:
            print('the error is %s'%e)
            result = {'code':20100,'error':'应户名或密码错误'}
            return JsonResponse(result)
        md5 = hashlib.md5()
        md5.update(password.encode())
        password_h = md5.hexdigest()

        if password_h != user.password:
            result = {'code':20101,
                      'error':'用户名或密码错误'}
            return JsonResponse(result)
        token = make_token(username)
        token = token.decode()
        return JsonResponse({'code':200,
                             'username':username,
                            'data':{'token':token}})